package com.tianluo.tianluobookstore.task;

import com.tianluo.tianluobookstore.OrderPO;
import com.tianluo.tianluobookstore.enums.OrderStatus;
import com.tianluo.tianluobookstore.enums.OrderStatusEnum;
import com.tianluo.tianluobookstore.enums.PaymentStatus;
import com.tianluo.tianluobookstore.service.OrderService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class OrderCancelTask implements Runnable {

    private final DelayQueue<OrderDelayItem> delayQueue = new DelayQueue<>();
    private final OrderService orderService;

    private ExecutorService executorService;

    @Autowired
    public OrderCancelTask(OrderService orderService) {
        this.orderService = orderService;
    }

    // 任务添加方法，添加到DelayQueue中
    public void addOrder(String orderId, long delayMillis) {
        delayQueue.put(new OrderDelayItem(orderId, delayMillis));
    }

    @PostConstruct
    public void start() {
        // 启动一个线程池执行cancel任务
        executorService = Executors.newSingleThreadExecutor();
        executorService.submit(this);  // 提交任务到线程池
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                // 从 DelayQueue 获取超时的订单任务
                OrderDelayItem item = delayQueue.take();
                String orderId = item.getOrderId();

                // 查询订单
                OrderPO order = orderService.queryOrderByOrderId(orderId);

                // 检查订单是否超时未支付且未取消
                if (order != null &&
                        Objects.equals(order.getPaymentStatus(), PaymentStatus.NOT_PAID.getCode()) &&
                        !order.getStatus().equals(OrderStatus.CANCELLED.getCode())) {

                    // 取消订单
                    orderService.cancelOrder(orderId);
                    System.out.println("订单超时取消，订单ID：" + orderId);
                }
            } catch (InterruptedException e) {
                // 如果线程被中断，退出
                Thread.currentThread().interrupt();
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
